package com.yztctech.a24_02_normalbroadcast_dynamicregist;

import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/***
 * 动态注册广播:这里做了一个动态注册广播下载数据的demo
 *   1、注册 registerReceiver(BroadcastReceiver var1, IntentFilter var2)
 *   2、解除注册 unregisterReceiver（BroadcastReceiver var1）
 *   3. 里边用到观察者模式,监听下载完成后通知Activity
 *
 * 数据交互-接口回调
 *
 * BroadcastReceiver也可以定义在Activity内部，便于数据交互
 * 备注:
 * 1. 动态和静态的区别:动态注册有生命周期的限制
 * 2. 注册和解除注册是配对使用的,否则报错
 * 3.
 */
public class MainActivity extends AppCompatActivity implements IDownloadListener{

    private TextView resultTv;

    private Button downloadBtn;

    private BroadcastReceiver downloadReceiver;//观察者

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initReceiver ();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除广播接收器的注册
        unregisterReceiver(downloadReceiver);
    }

    //注册广播接收器
    private void initReceiver() {
        downloadReceiver = new DownloadReceiver(this);
        IntentFilter filter = new IntentFilter(MyConstants.ACTION_DOWNLOAD);
//        filter.addAction("");
        registerReceiver(downloadReceiver, filter);//动态注册广播接收器
    }

    private void initView() {
        resultTv = (TextView) findViewById(R.id.tv_result);
        downloadBtn = (Button) findViewById(R.id.btn_download);
        downloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //发布一个广播
                new DownloadTask(getApplicationContext()).execute();//getApplicationContext()==Mainactivity.this
            }
        });
    }

    //Receiver的回调
    @Override
    public void success(String result) {
        if (!TextUtils.isEmpty(result)) {
            resultTv.setText(result);
        }
    }


}
